// pages/focus/index.js
const app = getApp();
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    strategyId: 0,
    strategy: [ '波动预警', '峰值预警' ],
    coins: ['btc', 'usdt'],
    tabCur: 0,
    menuBorder: true,
    symbols: [
      null, null
    ],
    searchWord: ''
  },

  tabSelect: function (e) {
    const newTab = e.currentTarget.dataset.id
    this.setData({
      tabCur: newTab
    })
    const symbols = this.data.symbols;
    if (symbols[newTab] == null) {
      this.querySymbolsWithStrategy();
      return;
    }
    this.searchSymbolsByKey(this.data.searchWord);
  },

  searchSymbols: function (e) {
    const key = e.detail.value;
    this.setData({
      searchWord: key
    })
    this.searchSymbolsByKey(key);
  },

  searchSymbolsByKey: function(key) {
    key = key.toLowerCase();
    const tabCur = this.data.tabCur;
    const symbols = this.data.symbols;
    let list = symbols[tabCur];
    list.forEach(o => {
      o.show = key == '' ? true : o.base.toLowerCase().includes(key)
    });
    // list.filter(o => o.toLowerCase().includes(key.toLowerCase()))
    symbols[tabCur] = list;
    this.setData(
       { symbols }
    )
  },

  focusSymbol: function(e) {
    const index = e.currentTarget.dataset.id;
    const tabCur = this.data.tabCur;
    const symbols = this.data.symbols;
    const item = symbols[tabCur][index];
    const state = item.focus;
    const strategyId = this.data.strategyId;
    if (state) {
      util.request.delete('/api/strategy/unfocus/' + strategyId + '/' + item.id)
    } else {
      util.request.post('/api/strategy/focus', {
        id: strategyId,
        symbolId: item.id,
      })
    }
    item.focus = !state;
        this.setData({ symbols });
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const strategyId = parseInt(options.id);
    this.setData({ strategyId })
    this.querySymbolsWithStrategy();
  },

  querySymbolsWithStrategy: function() {
    const tabCur = this.data.tabCur;
    const that = this;
    util.request.get('/api/strategy/' + this.data.strategyId, {
      categoryId: tabCur
    }).then(res => {
      const symbols = that.data.symbols;
      symbols[tabCur] = res;
      that.searchSymbolsByKey('');
      // that.setData({
      //   symbols
      // });
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})